import { onMounted, onUnmounted, ref } from 'vue'

export default function useScrollLoad(elRef: any) {
  const isLoading = ref(false)
  const isSearch = ref(false)
  const scrollTop = ref(0)
  const clientHeight = ref(0)
  const scrollHeight = ref(0)
  let el = window
  const handleScroll = () => {
    if (el === window) {
      scrollTop.value = document.documentElement.scrollTop
      clientHeight.value = document.documentElement.clientHeight
      scrollHeight.value = document.documentElement.scrollHeight
    } else {
      scrollTop.value = el.scrollTop
      clientHeight.value = el.clientHeight
      scrollHeight.value = el.scrollHeight
    }

    if (scrollTop.value > 720) {
      isSearch.value = true
    }
    if (scrollTop.value + clientHeight.value >= scrollHeight.value) {
      console.log('到底了')
      isLoading.value = true
    }
  }

  onMounted(() => {
    if (elRef) {
      el = elRef.value
    }
    el.addEventListener('scroll', handleScroll)
  })

  onUnmounted(() => {
    el.removeEventListener('scroll', handleScroll)
  })
  return {
    isLoading,
    isSearch,
    scrollTop,
  }
}
